package com.qianxun.module.base.util;

import com.qianxun.module.base.vo.MenuTreeVo;
import com.qianxun.module.datasource1.admin.entity.SysMenu;

import java.util.*;

/**
 * 菜单树转换工具
 * @author: huwei
 * @date: 2020/1/15 16:03
 * @version: 1.0.0
 */
public class MenuTreeVoUtil {

    /**
     * 将菜单列表转换为菜单树列表
     * @param sysMenuList
     * @param rootId
     * @return
     */
    public static List<MenuTreeVo> switchMenuTree(List<SysMenu> sysMenuList , long rootId){
        //整理菜单,做成pid到孩子节点的list映射，为做菜单树准备
        Map<Long ,List<SysMenu>> pidToChildrenMap = new HashMap<>(sysMenuList.size());
        sysMenuList.forEach(sysMenu -> {
            List<SysMenu> children = pidToChildrenMap.get(sysMenu.getPid());
            if(children == null){
                children = new ArrayList<>(16);
                pidToChildrenMap.put(sysMenu.getPid() ,children);
            }
            children.add(sysMenu);
        });

        //节点排序
        pidToChildrenMap.forEach((k ,v) ->{
            //排序
            Collections.sort(v ,(x , y)->{
                if(x.getSort() > y.getSort()){
                    return 1;
                }else if(x.getSort() < y.getSort()){
                    return -1;
                }
                return 0;
            });
        });

        List<MenuTreeVo> treeList = new ArrayList<>(sysMenuList.size());
        //整理菜单树，从根节点开始，即pid 为0
        List<SysMenu> rootMenu = pidToChildrenMap.get(rootId);
        if(rootMenu != null){
            treeList = wrapperMenuTree(rootMenu ,pidToChildrenMap);
        }

        return treeList;
    }

    private static List<MenuTreeVo> wrapperMenuTree(List<SysMenu> sysMenuList , Map<Long ,List<SysMenu>> pidToChildrenMap){
        List<MenuTreeVo> treeList = new ArrayList<>(sysMenuList.size());
        sysMenuList.forEach(sysMenu -> {
            MenuTreeVo sysMenuTreeVo = new MenuTreeVo(sysMenu.getId() ,sysMenu.getName() ,sysMenu.getUrl(),sysMenu.getIcon() ,sysMenu.getShowMode());
            List<SysMenu> children = pidToChildrenMap.get(sysMenu.getId());
            if(children != null){
                sysMenuTreeVo.setChildren(wrapperMenuTree(children ,pidToChildrenMap));
            }
            treeList.add(sysMenuTreeVo);
        });
        return treeList;
    }
}
